﻿using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kaskelot.SP.Core
{
    public class ULSLoggingService : SPDiagnosticsServiceBase
    {

        // You must create an event source with name DiagnosticAreaName in registry to log 
        private static string DiagnosticAreaName = "Kaskelot";
        private static string DiagnosticCategoryName = "Kaskelot SharePoint";
        private static ULSLoggingService _Current;
        public static ULSLoggingService Current
        {
            get
            {
                if (_Current == null)
                {
                    _Current = new ULSLoggingService();
                }

                return _Current;
            }
        }

        private ULSLoggingService()
            : base("Kaskelot Logging Service", SPFarm.Local)
        {

        }

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
            {
                new SPDiagnosticsArea(DiagnosticAreaName, new List<SPDiagnosticsCategory>
                {
                    new SPDiagnosticsCategory(DiagnosticCategoryName, TraceSeverity.Unexpected, EventSeverity.Error)
                })
            };

            return areas;
        }

        public static void LogError(string errorMessage)
        {
            SPDiagnosticsCategory category = ULSLoggingService.Current.Areas[DiagnosticAreaName].Categories[DiagnosticCategoryName];
            ULSLoggingService.Current.WriteTrace(0, category, category.DefaultTraceSeverity, errorMessage);
        }

        public static void LogWarningMessage(string errorMessage)
        {
            SPDiagnosticsCategory category = ULSLoggingService.Current.Areas[DiagnosticAreaName].Categories[DiagnosticCategoryName];
            ULSLoggingService.Current.WriteTrace(0, category, TraceSeverity.High, errorMessage);            
        }

        public static void LogVerboseMessage(string errorMessage)
        {
            SPDiagnosticsCategory category = ULSLoggingService.Current.Areas[DiagnosticAreaName].Categories[DiagnosticCategoryName];
            ULSLoggingService.Current.WriteTrace(0, category, TraceSeverity.Verbose, errorMessage);
        }
    }
}
